﻿using Csla.Core;
using Csla.Rules;
using System.Text.RegularExpressions;
using System;

namespace NetFrameworkExtensions.BusinessLayer.Csla4.Rules
{
  public class IsRegularExpressionRule : PropertyRule
  {

    public IsRegularExpressionRule(IPropertyInfo primaryProperty)
      : base(primaryProperty)
    {
      if (!primaryProperty.Type.IsAssignableFrom(typeof(string)))
        throw new ArgumentException("Property must accept string values");
    }

    protected override void Execute(RuleContext context)
    {
      string value = ReadProperty(context.Target, PrimaryProperty) as string;
      if (value != null)
      {
        try
        {
          new Regex(value);
        }
        catch (Exception ex)
        {
          string str = ex.Message;
          RuleResult ruleResult = new RuleResult(base.RuleName, this.PrimaryProperty, str);
          ruleResult.Severity = RuleSeverity.Error;
          context.Results.Add(ruleResult);
        }
      }
    }
  }
}
